<!-- 生产任务 -->
<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb"> </pageHeader>
  <div class="search-box">
    <a-space>
      <a-input-group>
        <a-select v-model="fields" :options="fieldsValue" :style="{ flex: 1 }">
        </a-select>
        <a-input
          @press-enter="search"
          :style="{ flex: 5 }"
          v-model="keyWord"
          :placeholder="`请输入${
            fieldsValue.filter((ele) => ele.value === fields)[0]?.label
          }`"
        />
      </a-input-group>
      <!-- <div style="margin-left: 20px; display: flex; align-items: center">
      <span style="margin-right: 20px">紧急程度</span>
      <a-input
        @press-enter="search"
        :style="{ flex: 5 }"
        v-model="keyWord"
        :placeholder="`请选择产品紧急程度`"
      />
    </div>
    <div style="margin-left: 20px; display: flex; align-items: center">
      <span style="margin-right: 20px">计划员</span>
      <a-input
        @press-enter="search"
        :style="{ flex: 5 }"
        v-model="keyWord"
        :placeholder="`请选择计划员`"
      />
    </div> -->
      <div>
        <span style="margin-right: 20px">计划日期</span>
        <a-range-picker
          style="width: 254px"
          v-model="resDate"
          show-time
          format="YYYY-MM-DD HH:mm"
          @ok="(e, a) => onOk(e as string[], a)"
          @clear="clear"
          value-format="x"
        />
      </div>
      <a-button
        @click="
          () => {
            keyWord = '';
            tableRef.loadData();
            taskDate.taskTimeGe = 0;
            taskDate.taskTimeLe = 0;
          }
        "
        type="outline"
      >
        <template #icon> <icon-sync size="18" /> </template>
        <template #default>重置 </template>
      </a-button>
      <a-button
        @click="tableRef.loadData()"
        type="primary"
        style="color: aliceblue"
      >
        <template #icon><icon-search size="18" /> </template>
        <template #default>搜索 </template>
      </a-button>
    </a-space>
    <a-space>
      <a-button
        @click="jumpFlowCard"
        style="background: #e8f7ff; color: #518cff"
      >
        <template #icon><icon-settings size="18" /> </template>
        <template #default>流程卡设置 </template>
      </a-button>
    </a-space>
  </div>
  <!-- <a-button @click="aaaaaa">test</a-button> -->
  <TableTurn
    :args="{
      rowSelection: {
        type: 'radio',
        showCheckedAll: true,
      },
    }"
    :table-data="getData"
    ref="tableRef"
    style="padding: 0 10px"
  >
    <a-table-column :width="70" align="center">
      <template #title> 序号 </template>
      <template #cell="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
    </a-table-column>
    <a-table-column
      :width="160"
      align="center"
      title="生产任务单号"
      data-index="code"
      :ellipsis="true"
      :tooltip="{
        position: 'top',
      }"
    >
    </a-table-column>
    <!-- <a-table-column :width="150" align="center" title="订单类型">
      <template #cell="{ record }">
        {{ record?.planModel?.workOrderModel?.workCode }}
      </template>
    </a-table-column> -->
    <a-table-column
      :width="150"
      align="center"
      title="关联生产工单编号"
      data-index="planProduceNumber"
      :ellipsis="true"
      :tooltip="{
        position: 'top',
      }"
    >
      <template #cell="{ record }">
        {{ record?.planModel?.workOrderModel?.workCode }}
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="产品编码"
      :ellipsis="true"
      :tooltip="{
        position: 'top',
      }"
    >
      <template #cell="{ record }">
        {{ record?.planModel?.workOrderModel?.product?.managementNumber }}
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="产品名称"
      :ellipsis="true"
      :tooltip="{
        position: 'top',
      }"
    >
      <template #cell="{ record }">
        {{ record?.planModel?.workOrderModel?.product?.managementName }}
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="规格型号"
      :ellipsis="true"
      :tooltip="{
        position: 'top',
      }"
    >
      <template #cell="{ record }">
        {{ record?.planModel?.workOrderModel?.product?.managementSpec }}
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="生产批次号"
      data-index="batchCode"
    >
    </a-table-column>
    <!-- <a-table-column
        :width="150"
        align="center"
        title="销售订单数量"
        data-index="repairerName"
      >
      </a-table-column> -->
    <a-table-column
      :width="150"
      align="center"
      title="基本单位"
      data-index="planProduceNumber"
    >
      <template #cell="{ record }">
        {{ record?.planModel?.workOrderModel?.product?.unit }}
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="计划任务数量"
      data-index="planTaskNumber"
    >
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="工单生产数量"
      data-index="repairerName"
    >
      <template #cell="{ record }">
        {{ record?.planModel?.workOrderModel?.produceNumber }}
      </template>
    </a-table-column>
    <a-table-column
      :width="250"
      align="center"
      title="任务单进度"
      data-index="repairerName"
    >
      <template #cell="{ record }">
        <template v-if="!record?.processGroups"> 暂无数据 </template>
        <template v-else-if="record?.processGroups?.length === 1">
          <div>
            <a-progress
              type="circle"
              size="medium"
              :percent="record?.processGroups[0]?.progress?.toFixed(2)"
            />
            <p style="font-size: 12px; padding: 0; margin: 0">
              {{ record?.processGroups[0]?.name }}
            </p>
          </div>
        </template>
        <template v-else>
          <div
            style="
              display: flex;
              align-items: center;
              width: 100%;
              overflow: auto;
            "
          >
            <div
              :class="{
                lastCss: index === record?.processGroups?.length - 1,
                cnCss:
                  index !== 0 && index !== record?.processGroups?.length - 1,
                first: index === 0,
              }"
              v-for="(item, index) in record?.processGroups"
              :key="item.id"
            >
              <!-- <div
                :style="{
                  display:
                    index !== 0 && index !== record.processGroups.length - 1
                      ? 'block'
                      : 'none'
                }"
                class="left"
              >
                ---</div
              > -->
              <div>
                <a-progress
                  size="medium"
                  type="circle"
                  :percent="item?.progress?.toFixed(2)"
                />
                <p
                  style="
                    font-size: 12px;
                    padding: 0;
                    margin: 0;
                    width: 80px;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                  "
                >
                  {{ item?.name }}
                </p>
              </div>
              <!-- <div
                :style="{
                  display:
                    index !== 0 && index !== record.processGroups.length - 1
                      ? 'block'
                      : 'none'
                }"
                class="right"
              >
                ---</div
              > -->
            </div>
          </div>
        </template>
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="良品数"
      data-index="repairerName"
    >
      <template #cell="{ record }">{{ record.aa }} - </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="不良品数"
      data-index="customName"
    >
      <template #cell="{ record }">{{ record.aa }} - </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="报废数量"
      data-index="planBeginAt"
    >
      <template #cell="{ record }">{{ record.aa }} - </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="紧急程度"
      data-index="planEndAt"
    >
      <template #cell="{ record }">
        <p
          :style="{
            color: emergencyLevel.filter(
              (i) =>
                i.id ===
                record.planModel?.workOrderModel?.produceOrder?.emergencyLevel
            )[0]?.color,
          }"
          >{{
            emergencyLevel.filter(
              (i) =>
                i.id ===
                record.planModel?.workOrderModel?.produceOrder?.emergencyLevel
            )[0]?.value
          }}
        </p>
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="工艺路线"
      data-index="repairerName"
      :ellipsis="true"
      :tooltip="{
        position: 'top',
      }"
    >
      <template #cell="{ record }">
        {{
          record?.planModel?.workOrderModel?.product?.productModel?.routerName
        }}
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="制造BOM"
      data-index="remark"
      :ellipsis="true"
      :tooltip="{
        position: 'top',
      }"
    >
      <template #cell="{ record }">
        {{ record?.planModel?.workOrderModel?.product?.bomName }}
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="计划开始日期"
      data-index="planBeginAt"
    >
      <template #cell="{ record }">
        {{ `${dayjs(record.beginAt).format('YYYY-MM-DD')}` }}
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="计划完工日期"
      data-index="planEndAt"
    >
      <template #cell="{ record }">
        {{ `${dayjs(record.endAt).format('YYYY-MM-DD')}` }}
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="计划员"
      data-index="status"
    >
      <template #cell="{ record }">
        {{ record?.planModel?.workOrderModel?.plannerId }}
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="生产主管"
      data-index="remark"
    >
      <template #cell="{ record }">{{ record.aa }} - </template>
    </a-table-column>
    <a-table-column
      :width="100"
      align="center"
      title="流转卡"
      data-index="remark"
    >
      <template #cell="{ record }">
        <!-- <p
          @click="jumpPreview(record.id)"
          style="color: #518cff; cursor: pointer"
        >
          查看
        </p> -->
        <a-tooltip content="查看">
          <IconFont
            type="icon-chakan1"
            :size="30"
            :style="{
              marginRight: '10px',
              cursor: 'pointer',
            }"
            @click="jumpPreview(record.id)"
          />
        </a-tooltip>
      </template>
    </a-table-column>
    <!-- <a-table-column
      :width="150"
      align="center"
      title="状态"
      data-index="remark"
    >
      <template #cell="{ record }">
      

        <div
          class="status"
          :style="{
            color: orderStatus.filter((ele) => ele.id === record.status)[0]
              ?.backgroundColor
          }"
        >
          <p
            :style="{
              'background': orderStatus.filter(
                (ele) => ele.id === record.status
              )[0]?.backgroundColor,
              'box-shadow': `0px 0px 5px`
            }"
          ></p>
          {{ showStatus(record.status) }}
  
        </div>
      </template>
    </a-table-column> -->
    <a-table-column
      :width="100"
      align="center"
      title="操作"
      fixed="right"
      data-index="remark"
    >
      <template #cell="{ record }">
        <!-- <a-button
          v-if="record?.mark === 1"
          :disabled="record.outsourcingAmount === record.planTaskNumber"
          @click="TransferOutsourcing(record)"
          type="text"
        >
          <template #default>创建工序委外 </template>
        </a-button> -->
        <a-tooltip
          v-if="
            record?.mark === 1 &&
            record.outsourcingAmount !== record.planTaskNumber
          "
          content="创建工序委外"
        >
          <IconFont
            type="icon-add-def"
            :size="26"
            :style="{
              marginRight: '10px',
              cursor: 'pointer',
            }"
            @click="TransferOutsourcing(record)"
          />
        </a-tooltip>
        <p v-else> — </p>
      </template>
    </a-table-column>
  </TableTurn>
</template>

<script lang="ts" setup>
  import { GetTaskPage } from '@/api/produce-management/produce-list/index';
  import dayjs from 'dayjs';
  import { reactive, ref } from 'vue';
  import pageHeader from '@/components/page-header/index.vue';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';

  let tableRef = ref();
  const fields = ref('code');
  const resDate = reactive<any[]>([]);
  const emergencyLevel = [
    { id: 1, value: '一般', color: '#009933' },
    { id: 2, value: '紧急', color: '#409eff' },
    { id: 3, value: '加急', color: '#ff8000' },
    { id: 4, value: '特急', color: '#ff0000' },
  ];
  const orderStatus = [
    { id: 1, value: '未开始', backgroundColor: '#cccccc' },
    { id: 2, value: '执行中', backgroundColor: '#3d7eff' },
    { id: 3, value: '已结束', backgroundColor: '#009933' },
  ];
  const fieldsValue = [
    { value: 'code', label: '生产任务单号' },
    // { value: 'keyword', label: '生产任务单号' },
    // { value: 'keyword', label: '生产任务单号' },
    // { value: 'customName', label: '生产任务单号' },
    // { value: 'keyword', label: '生产任务单号' }
    // { value: 'customName', label: '客户名称' }
  ];
  const keyWord = ref('');
  const router = useRouter();
  const title: string = '生产任务列表';
  const breadCrumb: string[] = ['生产管理', '生产任务'];
  const clientList: any = reactive({ data: [] });
  // 计划时间
  const taskDate = {
    taskTimeGe: 0, //左边
    taskTimeLe: 0, // 右边
  };

  // 获取表格数据
  const getData = async (pageData?: any) => {
    try {
      const search = {};
      const data: any = {};
      search[fields.value] = keyWord.value;
      if (
        taskDate.taskTimeGe &&
        taskDate.taskTimeLe &&
        taskDate.taskTimeGe < taskDate.taskTimeLe
      ) {
        data.beginAt = taskDate.taskTimeGe;
        data.endAt = taskDate.taskTimeLe;
      }
      const res = await GetTaskPage({ ...pageData, ...search, ...data });
      return Promise.resolve(res);
    } catch (error: unknown) {
      console.log(error);
    }
  };
  const jump = () => {
    router.push({ name: 'AddProductionOrder' });
  };

  const search = () => {
    //tableRef.loadData()
    tableRef.value.loadData();
  };
  const jumpFlowCard = () => {
    if (tableRef.value.selectedKeys.length === 1) {
      router.push({
        name: 'FlowCard',
        params: { id: tableRef.value.selectedKeys[0] },
      });
      const { code, id, planTaskNumber } = tableRef.value.selectedList[0];
      localStorage.setItem(
        'taskData',
        JSON.stringify({ code, id, planTaskNumber })
      );
    } else {
      Message.error('请选择生产任务');
    }
  };
  const showStatus = (status: number) => {
    const name = orderStatus.filter((ele) => ele.id === status)[0]?.value;
    if (name) return name;
    return '状态有问题';
  };
  const jumpPreview = (id: number) => {
    router.push({
      name: 'FlowCardPreview',
      query: { taskId: JSON.stringify(id) },
    });
  };

  const TransferOutsourcing = (res: any) => {
    sessionStorage.setItem('TransferProcessOutsourcing', JSON.stringify(res));
    router.push({ name: 'TransferProcessOutsourcing' });
  };

  const test = () => {
    let index = 0;
    // eslint-disable-next-line no-extend-native
    Array.prototype.map = function (callbackfn, thisArg) {
      // eslint-disable-next-line no-plusplus
      // console.log(index++, thisArg, Object(this));
      // 异常处理
      if (this == null) {
        throw new TypeError("Cannot read property 'map' of null or undefined");
      }
      // Step 1. 转成数组对象，有 length 属性和 K-V 键值对
      let O = Object(this);
      // Step 2. 无符号右移 0 位，左侧用 0 填充，结果非负
      // eslint-disable-next-line no-bitwise
      let len = O.length >>> 0;
      // Step 3. callbackfn 不是函数时抛出异常
      if (typeof callbackfn !== 'function') {
        throw new TypeError(callbackfn + ' is not a function');
      }
      // Step 4.
      let T = thisArg;
      // console.log('T', T);

      // Step 5.
      let A = new Array(len);
      // Step 6.
      let k = 0;
      // Step 7.
      while (k < len) {
        // Step 7.1、7.2、7.3
        // 检查 O 及其原型链是否包含属性 k
        if (k in O) {
          // Step 7.3.1
          let kValue = O[k];
          // Step 7.3.2 执行 callbackfn 函数
          // 传入 this, 当前元素 element, 索引 index, 原数组对象 O
          let mappedValue = callbackfn.call(T, kValue, k, O);
          // Step 7.3.3 返回结果赋值给新生成数组
          A[k] = mappedValue;
        }
        // Step 7.4
        // eslint-disable-next-line no-plusplus
        k++;
      }
      // Step 8. 返回新数组
      return A;
    };
  };
  function abc(this: any, ele: any, index: any, arr: any) {
    return console.log(ele);
  }
  const aaaaaa = () => {
    ['a', 'b', 'c'].map(abc, 1);
  };
  aaaaaa();
  test();
  aaaaaa();
  const onOk = (e: string[], a: Date[]) => {
    taskDate.taskTimeGe = +a[0];
    taskDate.taskTimeLe = +a[1];
    resDate[0] = e[0];
    resDate[1] = e[1];
    search();
  };
  const clear = () => {
    resDate[0] = null;
    resDate[1] = null;
    taskDate.taskTimeGe = 0;
    taskDate.taskTimeLe = 0;
    search();
  };
</script>

<style scoped lang="less">
  .search-box {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    padding: 10px;
    margin-top: -7px;
  }
  .status {
    display: flex;
    align-items: center;
    justify-content: center;

    p {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 10px;
    }
  }
  .lastCss {
    margin-left: 10px;
  }
  .first {
    margin-right: 10px;
  }
  .cnCss {
    margin: 0 10px;
    display: flex;
    align-items: center;
  }
</style>
